package com.springboot.example.mybatis.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 作者: guo yao
 * 日期: 2016年01月15日
 * 时间: 下午17:02
 */

@Aspect
@Component
public class AspectMvcInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AspectInterceptor.class);

    @Pointcut("execution(public * com.breadenglish.wechat.web..*(..))")
    public void pagingMvc() {
    }


    @Around("pagingMvc()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 判断是否是带有翻页注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(EnablePaging.class)) {
            checkEnablePaging(joinPoint);
        }
        return joinPoint.proceed();

    }

    private void checkEnablePaging(ProceedingJoinPoint joinPoint) throws Throwable {
//        logger.debug(method.getClass().getName() + " 是否是带有翻页的方法：" + method.isAnnotationPresent(EnablePaging.class));
        // 查找方法中是否有翻页参数
        QueryPage queryPage = null;
        for (Object obj : joinPoint.getArgs()) {
            if (QueryPage.class.isInstance(obj)) {
                queryPage = (QueryPage) obj;
                break;
            }
        }
        if (queryPage != null) {
            // 设置翻页参数
            addContextHolder(getPage(queryPage));
        }
    }

    /**
     * 获得翻页参数对象
     *
     * @param queryPage Query翻页参数
     * @return
     */
    protected Page getPage(QueryPage queryPage) {
        Page rollPage = new Page();
        //当前页
        Integer page = queryPage.getPage();
        int currentPage = (page != null && page > 0 ? page : 1);
        rollPage.setCurrentPage(currentPage);
        logger.debug("当前页数：[" + currentPage + "]");
        //每页显示条数
        Integer rows = queryPage.getRows();
        int pageSize = (rows != null && rows > 0 ? rows : 10);
        rollPage.setPageSize(pageSize);
        logger.debug("当前页显示条数：[" + pageSize + "]");
        return rollPage;
    }

    public void addContextHolder(Page rollPage) {
        // 设置翻页参数
        PagingContextHolder.setPage(rollPage);
    }

    public void clearContextHolder() {
        // 清理过期的翻页参数
        PagingContextHolder.removePage();
    }

}
